package com.hdl.dao.impl;

import com.hdl.config.ConfigurationCenter;
import com.hdl.dao.ResumeDao;
import com.hdl.utils.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * 类名 ResumeDaoImpl
 * 描述 TODO
 *
 * @author hedonglin
 * @version 1.0
 * @date 2020/6/18 21:59
 */
@Component
public class ResumeDaoImpl implements ResumeDao {
    @Override
    public Map<String, Object> getResumeById(Integer id) throws SQLException {
        DataSource dataSource = (DataSource) BeanFactory.getBean(ConfigurationCenter.CONFIG_CENTER_DATASOURCE);
        if (dataSource == null){
            System.out.println("获取数据源为空");
            return Collections.emptyMap();
        }

        // 1、获取一个数据库连接
        Connection connection = dataSource.getConnection();

        // 2、Sql准备
        String sql = "select id, address, name, phone from tb_resume where id = ?";

        // 3、预编译和参数准备
        PreparedStatement statement = connection.prepareStatement(sql);
        statement.setInt(1, id);

        // 4、执行查询
        ResultSet resultSet = statement.executeQuery();

        // 5、遍历查询结果
        Map<String, Object> resultMap = new HashMap<>();
        while (resultSet.next()){
            resultMap.put("id"  ,resultSet.getInt("id"));
            resultMap.put("address"  ,resultSet.getString("address"));
            resultMap.put("name"  ,resultSet.getString("name"));
            resultMap.put("phone"  ,resultSet.getString("phone"));
        }
        resultSet.close();
        statement.close();
        return resultMap;
    }
}
